package com.gitee.wsl.ext.math

import kotlin.math.abs
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.log10
import kotlin.math.pow
import kotlin.math.sign

fun List<Float>.autoScaleRange(): ClosedFloatingPointRange<Float> {
    val max = this.max()
    val min = this.min()
    val range = if (max - min == 0f) {
        if (min != 0f) {
            (max * 2f) - (min / 2f)
        } else {
            1f
        }
    } else {
        max - min
    }

    val scale = 10f.pow(floor(log10(range)))

    val scaleMin = if (min < 0) {
        ceil(abs(min / scale))
    } else {
        floor(abs(min / scale))
    } * scale * sign(min)

    val scaleMax = if (max > 0) {
        ceil(abs(max / scale))
    } else {
        floor(abs(max / scale))
    } * scale * sign(max)

    return if (scaleMax - scaleMin == 0f) {
        if (scaleMin != 0f) {
            scaleMin / 2f..scaleMax * 2f
        } else {
            scaleMin..1f
        }
    } else {
        scaleMin..scaleMax
    }
}

/*
fun List<Int>.autoScaleRange(): ClosedFloatingPointRange<Float> {
    val max = this.max()
    val min = this.min()
    val range = if (max - min == 0) {
        if (min != 0) {
            (max * 2f) - (min / 2f)
        } else {
            1f
        }
    } else {
        max - min
    }
    val scale = 10f.pow(floor(log10(range.toFloat())))

    val scaleMin = if (min < 0) {
        ceil(abs(min / scale))
    } else {
        floor(abs(min / scale))
    } * scale * sign(min.toFloat())

    val scaleMax = if (max > 0) {
        ceil(abs(max / scale))
    } else {
        floor(abs(max / scale))
    } * scale * sign(max.toFloat())

    return if (scaleMax - scaleMin == 0f) {
        if (scaleMin != 0f) {
            scaleMin / 2f..scaleMax * 2f
        } else {
            scaleMin..1f
        }
    } else {
        scaleMin..scaleMax
    }
}*/
